package com.yc.web;

import com.google.gson.Gson;
import com.yc.web.bean.Result;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * HandlerInterceptor SpringMVC 拦截器接口 ==> Servlet 的 Filter 过滤器
 * 对比:
 * 1. Fileter.doFilter 过于简单, 不方便控制
 * 2. 可以注入IOC容器中的 bean
 */
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * try {
     *     前置拦截
     *          控制器方法 login, withdraw ...
     *     后置拦截
     * } finally {
     *     完成拦截
     * }
     */


    /**
     * @param request  请求对象
     * @param response 响应对象
     * @param handler  控制器方法
     * @return boolean   表示请求是否到达目标资源( 控制器方法 ...)
     * @throws Exception
     */
    // 前置拦截
    @Override
    public boolean preHandle(
            javax.servlet.http.HttpServletRequest request,
            javax.servlet.http.HttpServletResponse response,
            Object handler) throws Exception {
        if (request.getSession().getAttribute("loginedUser") == null) {
            if (request.getHeader("Accept").startsWith("application/json")) {
                // json
                response.setContentType("application/json;charset=utf-8");
                Gson gson = new Gson();
                Result res = new Result(0, "请先登录系统", null);
                String json = gson.toJson(res);
                response.getWriter().append(json);
            } else {
                // 页面跳转 ==> 响应重定向
                response.sendRedirect("login.html");
            }
            return false;
        } else {
            return true;
        }

    }

    // 后置拦截
    /*@Override
    public void postHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }*/

    // 完成拦截
    /*@Override
    public void afterCompletion(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }*/
}
